package com.whccb.apps.office.document.service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.servicetask.ServiceDelegate;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.bpms.util.Base64;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.local.api.LogAPI;
import com.actionsoft.sdk.local.api.Logger;
import com.whccb.apps.office.document.ODConstant;
import com.whccb.apps.office.document.util.CMSUtil;
import com.whccb.apps.office.document.util.DictUtil;
import com.whccb.apps.office.document.util.FileUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class CreateCmsServiceAtFw extends ServiceDelegate {

	private static final Logger logger = LogAPI.getLogger(CreateCmsServiceAtFw.class);
	
	public String getDescription() {
		return "发文流程结束后，自动发布CMS内容。";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public boolean execute(ProcessExecutionContext pec) throws Exception {

		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(pec.getProcessInstance().getId());
		if (paramMap != null && !paramMap.isEmpty()) {
			String boName = paramMap.get("BONAME") != null ? paramMap.get("BONAME").toString() : "";

			String zhmoduleid = paramMap.get("ZHCMSMODULEID") != null ? paramMap.get("ZHCMSMODULEID").toString() : "";
			String fhmoduleid = paramMap.get("FHCMSMODULEID") != null ? paramMap.get("FHCMSMODULEID").toString() : "";
			String gxhmoduleid = paramMap.get("GXHCMSMODULEID") != null ? paramMap.get("GXHCMSMODULEID").toString() : "";

			String msgtype = paramMap.get("CMSMSGTYPE") != null ? paramMap.get("CMSMSGTYPE").toString() : "";
			String boldflag = paramMap.get("BOLDFLAG") != null ? paramMap.get("BOLDFLAG").toString() : "";

			String replyflag = paramMap.get("REPLYFLAG") != null ? paramMap.get("REPLYFLAG").toString() : "";
			String copyflag = paramMap.get("COPYFLAG") != null ? paramMap.get("COPYFLAG").toString() : "";
			String readflag = paramMap.get("READFLAG") != null ? paramMap.get("READFLAG").toString() : "";
			String zdflag = paramMap.get("ZDFLAG") != null ? paramMap.get("ZDFLAG").toString() : "";

			BO bo = SDK.getBOAPI().getByProcess(boName, pec.getProcessInstance().getId());
			if (bo != null) {
				String moduleid = "";
				String userDeptid = bo.getString("USERDEPTID");
				// 发文流程需要判断是总行发文/分行发文/管辖行发文.然后写到不同的cms区域。
				String at = "@getDeptExtInfo(@getSuperDept(" + userDeptid + "),ORGCATEGORY)";
				String deptType = SDK.getRuleAPI().executeAtScript(at);
				
				if (ODConstant.ZH_FLAG.equals(deptType)) {// 总行
					moduleid = zhmoduleid;
				}
				if (ODConstant.FH_FLAG.equals(deptType)) {// 分行
					moduleid = fhmoduleid;
				}
				if (ODConstant.GXH_FLAG.equals(deptType)) {// 管辖行
					moduleid = gxhmoduleid;
				}

				String title = "";
				if (StringUtils.isNotBlank(bo.getString("ODTYPE"))) {
					title = title + "<" + DictUtil.getDictValue("WHBK.OD.ODTYPE", bo.getString("ODTYPE")) + ">";
				}

				if (StringUtils.isNotBlank(bo.getString("SUBJECT"))) {
					title = title + bo.getString("SUBJECT");
				}

				if (StringUtils.isNotBlank(moduleid) && StringUtils.isNotBlank(msgtype)) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("createuser", pec.getProcessInstance().getCreateUser());
					params.put("createtime", new Timestamp(System.currentTimeMillis()));
					params.put("moduleid", moduleid);
					params.put("msgtype", msgtype);
					params.put("title", title);
					params.put("boldflag", boldflag);
					params.put("replyflag", replyflag);
					params.put("copyflag", copyflag);
					params.put("readflag", readflag);
					params.put("zdflag", zdflag);

					List<FormFile> formFiles = FileUtil.getBoFieldFormFile(boName, "ZW", pec.getProcessInstance().getId());
					
					if (CollectionUtils.isNotEmpty(formFiles)) {
						JSONArray attachmentList = new JSONArray();
						for (FormFile formFile : formFiles) {
							if (formFile != null) {
								JSONObject attachmentMap = new JSONObject();
								attachmentMap.put("fileName", formFile.getFileName());
								attachmentMap.put("fileoldname", formFile.getFileName());
								InputStream is = null;
								ByteArrayOutputStream swapStream = null;
								try {
									DCContext contentDc = new DCContext(UserContext.fromUID("admin"),
											DCProfileManager.getDCProfile(formFile.getAppId(), "!iweboffice-"),
											formFile.getAppId(), formFile.getProcessInstId(), formFile.getBoItemName(),
											formFile.getFileName());

									if (contentDc != null) {
										is = SDK.getDCAPI().read(contentDc);
									}
									swapStream = new ByteArrayOutputStream();
									byte[] buf = new byte[1024];
									int rc = 0;
									while ((rc = is.read(buf, 0, 1024)) > 0) {
										swapStream.write(buf, 0, rc);
									}
									byte[] bytedata = swapStream.toByteArray();

									attachmentMap.put("data", new String(Base64.encode(bytedata)));
									attachmentList.add(attachmentMap);
								} catch (Exception e) {
									logger.error("发文异常", e);
									throw new Exception("发文异常！");
								} finally {
									try {
										is.close();
										swapStream.close();
									} catch (Exception e) {
										logger.error("发文，关闭IO流异常！", e);
										throw new Exception("发文，关闭IO流异常！");
									}
								}
							}
							break;
						}
						params.put("attachment", attachmentList);
					}

					String readscopedesc = "";
					if (StringUtils.isNotBlank(bo.get("FILETO").toString())) {
						readscopedesc += bo.get("FILETO").toString() + ",";
					}
					if (StringUtils.isNotBlank(bo.get("FILECC").toString())) {
						readscopedesc += bo.get("FILECC").toString() + ",";
					}
					if (StringUtils.isNotBlank(readscopedesc)) {
						readscopedesc = readscopedesc.substring(0, readscopedesc.lastIndexOf(","));
					}

					params.put("readscopedesc", readscopedesc);

					String readscopeid = "";
					if (bo.get("TOID") != null && StringUtils.isNotBlank(bo.get("TOID").toString())) {
						readscopeid += bo.get("TOID").toString() + ",";
					}
					if (bo.get("CCID") != null && StringUtils.isNotBlank(bo.get("CCID").toString())) {
						readscopeid += bo.get("CCID").toString() + ",";
					}
					if (StringUtils.isNotBlank(readscopeid)) {
						readscopeid = readscopeid.substring(0, readscopeid.lastIndexOf(","));
					}

					CMSUtil.createCms(params, boName, bo.getId(), pec.getProcessInstance().getId(), readscopeid);
				}

			}

		}
		return true;
	}
}
